package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @description:用户业务层
 * @author: wangjingliang
 * @create: 2019-11-24 18:36
 **/
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //根据用户名查询用户信息角色及权限
    @Override
    public User selectByUsername(String username){
        //先用username查询获取用户信息
        User user=userMapper.selectByUsername(username);

        //根据用户id查询角色
        Set<Role> roles= roleMapper.selectByUserId(user.getId());

        for (Role role : roles) {
            //根据角色的id查询权限
            Set<Permission> permissions= permissionMapper.selectByRoleId(role.getId());
            role.setPermissions(permissions);
        }

        user.setRoles(roles);

        return user;

    }

    @Override
    public void add(User user) {


        try {
            userMapper.inselect(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(MessageConstant.EXCEPION);
        }
    }
}
